// pages/reading/reading.js
var util = require("../../utils/util.js");
Page({
    //分享
    onShareAppMessage: function () { },
    /**
     * 页面的初始数据
     */
    data: {
        picWidth:0,
        images:{},//添加图片
        defaultImage:"../../images/add.png",//若没有选择图片则默认显示这张
        showModal:false,
        type:"",
        typeName:"",
        comment_index: 'aa',
        inputValue: "",//评论内容
        defaultComment: "评论",
        updatePath:[],
        pageNumber:1,
        readMoreFlag:false,
        textareaValue:"",
        levelActive:"0",
        level1: [
            {},
            { name: "V1勋章", type: 1, url: "../../images/xunzhang/rank1.png", active: "../../images/xunzhang/rank11.png", checked: false, day: 7 },
            { name: "V2勋章", type: 2, url: "../../images/xunzhang/rank2.png", active: "../../images/xunzhang/rank22.png", checked: false, day: 21 },
            { name: "V3勋章", type: 3, url: "../../images/xunzhang/rank3.png", active: "../../images/xunzhang/rank33.png", checked: false, day: 45 },
            { name: "V4勋章", type: 4, url: "../../images/xunzhang/rank4.png", active: "../../images/xunzhang/rank44.png", checked: false, day: 69 },
            { name: "V5勋章", type: 5, url: "../../images/xunzhang/rank5.png", active: "../../images/xunzhang/rank55.png", checked: false, day: 98 },
            { name: "V6勋章", type: 6, url: "../../images/xunzhang/rank6.png", active: "../../images/xunzhang/rank66.png", checked: false, day: 121 },
            { name: "V7勋章", type: 7, url: "../../images/xunzhang/rank7.png", active: "../../images/xunzhang/rank77.png", checked: false, day: 145 },
            { name: "V8勋章", type: 8, url: "../../images/xunzhang/rank8.png", active: "../../images/xunzhang/rank88.png", checked: false, day: 196 },
            { name: "V9勋章", type: 9, url: "../../images/xunzhang/rank9.png", active: "../../images/xunzhang/rank99.png", checked: false, day: 200 },
            {},
            { name: "阅读新星", type: 11, url: "../../images/xunzhang/xz1.png", active: "../../images/xunzhang/xz11.png", checked: false, day: 21 },
            { name: "阅读达人", type: 12, url: "../../images/xunzhang/xz2.png", active: "../../images/xunzhang/xz22.png", checked: false, day: 45 },
            { name: "运动新星", type: 13, url: "../../images/xunzhang/xz3.png", active: "../../images/xunzhang/xz33.png", checked: false, day: 21 },
            { name: "运动达人", type: 14, url: "../../images/xunzhang/xz4.png", active: "../../images/xunzhang/xz44.png", checked: false, day: 45 },
            { name: "美食新星", type: 15, url: "../../images/xunzhang/xz5.png", active: "../../images/xunzhang/xz55.png", checked: false, day: 21 },
            { name: "美食达人", type: 16, url: "../../images/xunzhang/xz6.png", active: "../../images/xunzhang/xz66.png", checked: false, day: 45 }
        ],
        isSign:"1"
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        var system = wx.getSystemInfoSync();
        var width = system.screenWidth;
        var userInfo = JSON.parse(wx.getStorageSync("userInfo"));
        var type = options.type;
        var typeName = "";
        switch(type){
            case "1": typeName = "运动"; break;
            case "2": typeName = "饮食"; break;
            case "3": typeName = "阅读"; break;
        }
        this.setData({
            picWidth:width*0.17333,
            type: options.type,
            typeName: typeName,
            userInfo: userInfo
        });
        this.getDetail();
    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },
    //选择图片
    addPicture:function(options){
        var type = options.currentTarget.dataset.flag;
        var images = this.data.images;
        var that = this;
        wx.chooseImage({
            count: 1,
            sizeType: ['original', 'compressed'],
            sourceType: ['album', 'camera'],
            success(res) {
                let tempFilePaths = res.tempFilePaths[0];
                images[type] = tempFilePaths;
                that.setData({
                    images:images
                });
            }
        })
    },
    //打开签到模态框
    openModal:function(options){
        var flag = options.currentTarget.dataset.flag;
        if(!flag){
            this.setData({
                textareaValue:"",
                images:{}
            });
        }
        this.setData({
            showModal:new Boolean(flag),
        });
    },
    //获取详情
    getDetail:function(){
        var that = this;
        var type = this.data.type;
        var userInfo = JSON.parse(wx.getStorageSync("userInfo"));
        util.wxAjax("glHabit/habitList","post",{
            "adminid": userInfo.smAdmin.id,//用户id值
            "type": type,//习惯类型   1运动  2饮食   3阅读
        },function(res){
            var data = res.data;
            if(data.result == 200 || data.result == "200"){
                that.setData({
                    signin: data.data.signin + "",
                    isSignin: data.data.isSignin,
                    isSign:data.data.isSign
                });
                if(data.data.habit.length > 0){
                    for(let i=0;i<data.data.habit.length;i++){
                        if (!!data.data.habit[i].img && data.data.habit[i].img != ""){
                            data.data.habit[i].img = data.data.habit[i].img.split("|");
                        }
                    }
                    that.setData({
                        habit: data.data.habit,
                        readMoreFlag: (data.data.habit.length>19?true:false),
                    });
                }else{
                    wx.showToast({
                        title: '暂没有信息~',
                        icon:"none"
                    })
                }
            }else{
                wx.showToast({
                    title:data.msg,
                    icon:"none"
                });
            }
        });
    },
    //获取更多评论
    getMoreComment:function(){
        var that = this;
        var userInfo = JSON.parse(wx.getStorageSync("userInfo"));
        var pageNum = this.data.pageNumber;
        var habit = this.data.habit;
        util.wxAjax("glHabit/moreHabitList","post",{
            adminid: userInfo.smAdmin.id,
            type:this.data.type,
            pageNum:pageNum
        },function(res){
            var data = res.data;
            if(data.result == 200 || data.result == "200"){
                for (let i = 0; i < data.data.length; i++) {
                    if (data.data[i].img != "" && !!data.data[i].img) {
                        data.data[i].img = data.data[i].img.split("|");
                    }
                }
                habit = habit.concat(data.data);
                that.setData({
                    habit:habit,
                    readMoreFlag:(data.data.length>19?true:false)
                });
            }
        });
    },
    //显示评论框
    show_comment(e) {
        var index = e.currentTarget.dataset.index;
        this.setData({
            inputValue: "",
            comment_index: !!index || index == 0 ? index : "aa",
            defaultComment: "评论"
        });
    },
    //图片预览
    prevPicture: function (options) {
        var images = options.currentTarget.dataset.image;
        if(!images || images == ""){
            wx.showToast({
                title: '暂没有图片',
                icon:"none"
            })
        }
        wx.previewImage({
            urls: images,
            success: function (res) {}
        });
    },
    //对评论点赞
    dianzan: function (e) {
        var id = e.currentTarget.dataset.id;
        var userInfo = JSON.parse(wx.getStorageSync("userInfo")).smAdmin.id;
        var index = e.currentTarget.dataset.index;
        var habit = this.data.habit;
        let that = this;
        util.wxAjax("glHabit/updateLaudsAddOne", "post", {
            adminid: userInfo,
            id: id
        }, function (res) {
            var data = res.data;
            if (data.result == 200 || data.result == "200") {
                habit[index].lauds = habit[index].lauds * 1 + 1;
                habit[index].isLauds = 1;
                that.setData({
                    habit: habit
                });
            } else {
                wx.showToast({
                    title: data.msg,
                    icon: "none"
                })
            }
        })
    },
    payAttention: function (e) {
        var publishId = e.currentTarget.dataset.id;
        var userInfo = JSON.parse(wx.getStorageSync("userInfo")).smAdmin.id;
        if (publishId === userInfo) {
            wx.showToast({
                title: '不能关注自己~',
                icon: "none"
            });
            return false;
        }
        var type = e.currentTarget.dataset.type;
        var habit = this.data.habit;
        var index = e.currentTarget.dataset.index;
        var url = "admin/addFollow";
        var that = this;
        if (type == "1" || type == 1) {
            url = "admin/cancelFollow";
        }
        util.wxAjax(url, "post", {
            adminid: userInfo,
            fansid: publishId
        }, function (res) {
            var data = res.data;
            if (data.result == 200 || data.result == "200") {
                var returMsg = type == "0" || type == 0 ? "关注成功！" : "取消关注成功！";
                wx.showToast({
                    title: returMsg
                });
                that.getDetail();
                // habit[index].isFollow = type == "1" || type == 1 ? "0" : "1";
                // that.setData({
                //     habit: habit
                // });
            } else {
                wx.showToast({
                    title: data.msg,
                    icon: "none"
                })
            }
        })
    },
    //添加评论
    addComment: function (options) {
        var username = JSON.parse(wx.getStorageSync("userInfo")).smAdmin.name;
        var id = options.currentTarget.dataset.id;
        var index = options.currentTarget.dataset.index;
        var inputValue = this.data.inputValue;
        var habit = this.data.habit;
        var toName = this.data.defaultComment;
        var userInfo = JSON.parse(wx.getStorageSync("userInfo"));
        var that = this;
        if (!typeof (inputValue) || inputValue == "") {
            wx.showToast({
                title: '请输入评论内容！',
                icon: "none"
            })
            return false;
        }
        util.wxAjax("glHabit/updateCommentsAddOne", "post", {
            fromName: username,
            toName: toName,
            id: id,
            content: inputValue,
            adminid: userInfo.smAdmin.id
        }, function (res) {
            var data = res.data;
            if (data.result == 200 || data.result == "200") {
                that.setData({
                    inputValue: "",
                    defaultComment: "评论"
                });
                habit[index].habitcommon = habit[index].habitcommon.concat(data.data);
                that.setData({
                    habit: habit
                });
            } else {
                wx.showToast({
                    title: data.msg,
                    icon: "none"
                })
            }
        })
    },
    //绑定input值
    setValue: function (options) {
        var type = options.currentTarget.dataset.type;
        var value = options.detail.value;
        this.setData({
            [type]: value
        });
    },
    //评论回复的评论
    pinglunRen: function (options) {
        var name = options.currentTarget.dataset.name;
        var userInfo = JSON.parse(wx.getStorageSync("userInfo"));
        if (name === userInfo.smAdmin.name) {
            this.setData({
                defaultComment: "评论",
                inputValue: ""
            });
        } else {
            this.setData({
                defaultComment: name,
                inputValue: ""
            });
        }
    },
    //提交签到信息
    submitQianDao:function(options){
        var content = this.data.textareaValue;
        var imgs = this.data.images;
        var temp = [];
        var flag = options.currentTarget.dataset.type;
        if(flag != "zhijie"){
            if (content == "" || !content) {
                wx.showToast({
                    title: '请输入签到内容！',
                    icon: "none"
                });
                return false;
            }
            for (var val in imgs) {
                temp.push(imgs[val]);
            }
        }
        this.uploadImg(temp,{},0);
    },
    //上传图片
    uploadImg: function (data, jsonData, i) {
        var HEADER = util.HEADER;
        var that = this,
            success = data.success ? data.success : 0,//上传成功的个数
            fail = data.fail ? data.fail : 0;//上传失败的个数
        if(data.length < 1){
            that.submitQiandao();
            return false;
        }
        wx.uploadFile({
            url: HEADER + 'admin/uploadImg', //仅为示例，非真实的接口地址
            filePath: data[i],
            name: 'file',
            formData: {},
            header: { "Content-Type": "multipart/form-data" },
            success: function (res) {
                var data = JSON.parse(res.data);
                if (data.result == 200 || data.result == "200") {
                    var oldArr = that.data.updatePath;
                    oldArr.push(data.data);
                    that.setData({
                        updatePath: oldArr
                    });
                }
            },
            fail: function () {
                fail++;//图片上传失败，图片上传失败的变量+1
            },
            complete: function () {
                i++;//这个图片执行完上传后，开始上传下一张
                if (i == data.length) {   //当图片传完时，停止调用   
                    that.submitQiandao();
                } else {//若图片还没有传完，则继续调用函数
                    data.i = i;
                    data.success = success;
                    data.fail = fail;
                    that.uploadImg(data, jsonData, i);
                }
            }
        });
    },
    //提交签到消息
    submitQiandao: function (){
        var that = this;
        var content = that.data.textareaValue;
        var uploadPath = that.data.updatePath;
        var userInfo = JSON.parse(wx.getStorageSync("userInfo"));
        var type = that.data.type;
        var jsonData = {};
        if (!!uploadPath && uploadPath!=""){
            jsonData.img = uploadPath.join("|");
        }
        jsonData.adminid = userInfo.smAdmin.id;
        jsonData.adminname = userInfo.smAdmin.name;
        jsonData.content = content;
        jsonData.type = type;
        util.wxAjax("glHabit/save", "POST", jsonData, function (res) {
            var data = res.data;
            if (data.result == 200 || data.result == "200") {
                wx.showToast({
                    title: '签到成功！',
                })
                that.setData({
                    showModal: false,
                    textareaValue: "",
                    images: {},
                    updatePath:[],
                    levelActive: data.data.decorated
                });
                that.getDetail();
            } else {
                wx.showToast({
                    title: data.msg,
                    icon: "none"
                })
            }
        });
    },
    //上拉刷新
    onPullDownRefresh: function () {
        // 显示顶部刷新图标  
        wx.showNavigationBarLoading();
        this.setData({
            pageNumber: 1,
            detail: {}
        });
        this.getdetail();
    },
    //下拉加载
    onReachBottom: function () {
        var flag = this.data.readMoreFlag;
        if (flag) {
            var pageNum1 = this.data.pageNumber;
            // 显示加载图标  
            wx.showLoading({
                title: '玩命加载中',
            })
            this.setData({
                pageNumber: ++pageNum1,
            });
            this.getMoreComment();
        }
    },
    //删除动态
    deleteMsg: function (options) {
        var that = this;
        var id = options.currentTarget.dataset.id;
        var index = options.currentTarget.dataset.index;
        var habit = this.data.habit;
        wx.showModal({
            title: '提示信息',
            content: '确认要删除该动态？',
            success: function (res) {
                if (res.confirm) {
                    util.wxAjax("glHabit/habitDelete", "post", {
                        id: id
                    }, function (res) {
                        var data = res.data;
                        if (data.result == 200 || data.result == "200") {
                            habit.splice(index, 1);
                            wx.showToast({
                                title: '删除成功！',
                            })
                            that.setData({
                                habit: habit
                            });
                        } else {
                            wx.showToast({
                                title: data.msg,
                                icon: "none"
                            })
                        }
                    });
                }
            }
        })
    },
    //删除评论
    deleteComment: function (options) {
        var that = this;
        var id = options.currentTarget.dataset.id;
        var index = options.currentTarget.dataset.index;
        var parIndex = options.currentTarget.dataset.parindex;
        var habit = this.data.habit;
        var userInfo = JSON.parse(wx.getStorageSync("userInfo"));
        wx.showModal({
            title: '确认信息',
            content: '确认要删除当前评论吗？',
            success: function (res) {
                if(res.confirm){
                    util.wxAjax("glHabit/deleteCommon", "post", {
                        id: id,
                        adminid: userInfo.smAdmin.id
                    }, function (res) {
                        var data = res.data;
                        if (data.result == 200 || data.result == "200") {
                            habit[parIndex].habitcommon.splice(index, 1);
                            that.setData({
                                habit: habit
                            });
                            wx.showToast({
                                title: '删除成功！',
                                icon: "none"
                            })
                        } else {
                            wx.showToast({
                                title: data.msg,
                                icon: "none"
                            })
                        }
                    })
                }
            }
        });
    },
    hide_xz:function(){
        this.setData({
            levelActive:"0"
        });
    }
})